#include <stdio.h>
#include <algorithm>
using namespace std;
 
int dp[10005]; int v;
 
 //01背包
void zp(int dp[], int w , int c) {
    for (int j = v; j >= w; j--)
        dp[j] = max(dp[j], dp[j-w] + c);
    return;
}
 
//完全背包
void cp(int dp[], int w, int c) {
    for (int j = w; j <= v; j++)
        dp[j] = max(dp[j], dp[j-w] + c);
    return;
}

//多重背包（整合）
void mp(int dp[], int w , int c , int amount) {
    if (w * amount >= v || amount == 0) {
        cp(dp, w, c);
        return;
    }
    for (int k = 1; k <= amount; k <<= 1) {
        zp(dp, w*k, c*k);
        amount -= k;
    }
    zp(dp, amount*w, amount*c);
    return;
}
 
int main() {
    int t1, t2, t3, t4, n, w, c, a;
    
    scanf("%d:%d %d:%d %d\n", &t1, &t2, &t3, &t4, &n);		//读入
    
    v = t3 * 60 + t4 - t1 * 60 - t2;
    
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", &w, &c, &a);
        if (a == 0) 
            cp(dp, w, c);
        else mp(dp, w, c, a);
    }
    
    printf("%d\n", dp[v]);
    return 0;
}